//
//  SearchNews.m
//  
//
//  Created by 微 醺 on 15/10/6.
//
//

#import "SearchNews.h"
#import "HomePageHeaderView.h"
#import "NetworkHandle.h"
#import "TopSearchTableViewCell.h"
#import "TopSearchModel.h"
#import "WebViewController.h"

@interface SearchNews () <UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) HomePageHeaderView *topSearchHeaderView;
@property (nonatomic, strong) WebViewController *webVC;
@property (nonatomic, retain) UISearchBar *searchBar;
@property (nonatomic, strong) NSDictionary *contentDic;
@property (nonatomic, strong) NSMutableArray *contentArr;
@property (nonatomic, strong) UITableView *searchResultTableView;
@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;
@property (nonatomic, assign) NSInteger webOffSet;
@property (nonatomic, strong) UIButton *cancelButton;

@end

@implementation SearchNews

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self topSearchHeader];
    [self tableViewSubViews];
    [self setupRefresh];
    
    self.webOffSet = 1;
    /*设置进度条*/
    self.indicatorView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:0];
    self.indicatorView.frame = CGRectMake(0, 0, SAWindth * 50 ,  SAHeight *50);
    self.indicatorView.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2);
    self.indicatorView.hidesWhenStopped = YES;
    self.indicatorView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:self.indicatorView];

    
}

#pragma mark - 刷新方法
- (void) setupRefresh
{
    
    /*下拉加载*/
    MJRefreshAutoFooter *footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    footer.automaticallyRefresh = YES;
    self.searchResultTableView.footer = footer;
    [self.searchResultTableView.footer beginRefreshing];
    
    
}

#pragma mark - 上拉加载zz
- (void) loadMoreData
{
    self.webOffSet = 2;
    NSString *bodyStr = [NSString stringWithFormat:@"page=%ld&searchContent=%@" , (long)self.webOffSet,self.searchBar.text];

    [NetworkHandle POSTWithURL:self.searchURLString httpBody:bodyStr complication:^(id result) {
        
        self.contentDic = result;
        if (self.searchType == 1) {
            
            NSArray *arr = [self.contentDic objectForKey:@"newsList"];
            for (int i = 0; i < arr.count; i++) {
                NSDictionary *dic = arr[i];
                
                [self.contentArr addObject:dic];
                
            }
            [self.searchResultTableView reloadData];
            [self.searchResultTableView.footer endRefreshing];
        }
        else
        {
            
            NSArray *arr = [self.contentDic objectForKey:@"postList"];
            for (int i = 0; i < arr.count; i++) {
                NSDictionary *dic = arr[i];
                
                [self.contentArr addObject:dic];
                
            }
            
            [self.searchResultTableView reloadData];
            [self.searchResultTableView.footer endRefreshing];
            
        }

        
    }];
    
    self.webOffSet = self.webOffSet + 1;
    
}

#pragma mark - 自定义header
- (void) topSearchHeader
{
    self.topSearchHeaderView = [[HomePageHeaderView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,80)];
    [self.topSearchHeaderView.setupButton removeFromSuperview];
    [self.topSearchHeaderView.logo removeFromSuperview];
    [self.view addSubview:self.topSearchHeaderView];
    [self.topSearchHeaderView addTarget:self selector:@selector(tapTopSearchHeaderView)];
    
    /*搜索按钮*/
    self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(10.0/375*self.topSearchHeaderView.frame.size.width, SAHeight * 15, 300.0/375*self.topSearchHeaderView.frame.size.width, SAHeight * 60)];
    self.searchBar.searchBarStyle = 0;
    self.searchBar.layer.borderWidth = 15;
    self.searchBar.layer.borderColor = [UIColor colorWithRed:141 / 255.0 green:162 / 255.0 blue:160 / 255.0 alpha:1].CGColor;
    self.searchBar.layer.cornerRadius = 20;
    self.searchBar.layer.masksToBounds = YES;
    self.searchBar.showsSearchResultsButton = NO;
    self.searchBar.showsCancelButton  = NO;
    self.searchBar.delegate = self;
    if (self.searchType == 1)
    {
        self.searchBar.placeholder = @"请输入新闻关键字";
    }
    [self.topSearchHeaderView addSubview:self.searchBar];

    
    /*取消按钮*/
    self.cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.cancelButton.frame = CGRectMake(300.0/375*self.topSearchHeaderView.frame.size.width, SAHeight * 28, 60.0/375*self.topSearchHeaderView.frame.size.width, SAHeight * 35);
    [self.cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [self.cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.cancelButton.titleLabel.font = [UIFont systemFontOfSize:18];
    [self.topSearchHeaderView addSubview:self.cancelButton];
    
    [self.cancelButton addTarget:self action:@selector(clickCancelButton:) forControlEvents:UIControlEventTouchUpInside];
    
    
}
- (void) clickCancelButton:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - 点击header,回到顶部
- (void) tapTopSearchHeaderView
{
    [self.searchResultTableView setContentOffset:CGPointMake(0, 0) animated:YES];
}

#pragma mark - 设置tabeView
- (void) tableViewSubViews
{
    self.searchResultTableView = [[UITableView alloc]initWithFrame:CGRectMake(0,  SAHeight * 80, self.view.frame.size.width, self.view.frame.size.height-2*self.tabBarController.tabBar.frame.size.height) style:UITableViewStylePlain];
    self.searchResultTableView.showsVerticalScrollIndicator = NO;
    self.searchResultTableView.separatorStyle = 0;
    self.searchResultTableView.delegate = self;
    self.searchResultTableView.dataSource = self;
    [self.view addSubview:self.searchResultTableView];
    
    [self.searchResultTableView registerClass:[TopSearchTableViewCell class] forCellReuseIdentifier:@"reuse"];
    
}

#pragma mark - tableView行数
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.contentArr.count;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return SAHeight * 150;
}

#pragma mark - tableViewCell
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.searchType == 1) {
        
        TopSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
        TopSearchModel *model = [[TopSearchModel alloc]init];
        NSDictionary *dic = self.contentArr[indexPath.row];
        [model setValuesForKeysWithDictionary:dic];
        cell.model = model;
        cell.selectionStyle = 0;
        [self.indicatorView stopAnimating];
        
        return cell;
    }
    else
    {
        TopSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];

        TopSearchModel *model = [[TopSearchModel alloc]init];
        model.newsTitle = [self.contentArr[indexPath.row] objectForKey:@"postTitle"];
        model.newsDesc = [self.contentArr[indexPath.row] objectForKey:@"postDesc"];
        model.newsCategory = [self.contentArr[indexPath.row] objectForKey:@"author"];
        
        cell.model = model;
        cell.selectionStyle = 0;
        [self.indicatorView stopAnimating];
        
        return cell;
        
    }
}


#pragma mark - 点击搜索
- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    
    NSString *bodyStr = [NSString stringWithFormat:@"page=1&searchContent=%@" , self.searchBar.text];
    
    AFNetworkReachabilityManager *managerStatus = [AFNetworkReachabilityManager sharedManager];
    if (managerStatus.reachable) {
        [self.indicatorView startAnimating];
        
        [NetworkHandle POSTWithURL:self.searchURLString httpBody:bodyStr complication:^(id result) {
            
            self.contentDic = result;

            if (result == nil) {
                [self.indicatorView stopAnimating];
            }
            if (self.searchType == 1) {
                
                self.contentArr = [self.contentDic objectForKey:@"newsList"];
            }
            else
            {
                self.contentArr = [self.contentDic objectForKey:@"postList"];
            }
            
            if (self.contentArr.count == 0)
            {
                [self.indicatorView stopAnimating];
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"对不起" message:@"搜索结果为空" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:0 handler:^(UIAlertAction *action) {
                    [alert dismissViewControllerAnimated:YES completion:^{
                        
                    }];
                }];
                [alert addAction:confirmAction];
                
                [self presentViewController:alert animated:YES completion:^{
                    
                }];
                
            }
            
            [self.searchResultTableView reloadData];
            
        }];

    }
    else{
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前网络无连接" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [alert dismissViewControllerAnimated:YES completion:^{
                
            }];
        }];
        
        [alert addAction:action];
        [self.navigationController presentViewController:alert animated:YES completion:^{
            
        }];
        
    }

}
#pragma mark - 点击cell跳转
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.searchBar resignFirstResponder];
    
    if (self.searchType == 1)
    {
        
        NSString *URLStr = [self.contentArr[indexPath.row] objectForKey:@"webLink"];
        
        if (self.webVC == nil)
        {
            self.webVC = [[WebViewController alloc]init];
            self.webVC.viewUrl = URLStr;
//            self.webVC.viewTitle = [self.contentArr[indexPath.row] objectForKey:@"newsTitle"];
            self.webVC.viewTitle = @"搜索详情";
            self.webVC.viewType = @"news";
            self.webVC.weiXun = @"WeiXun";
        }
        else
        {

            self.webVC = nil;
            self.webVC = [[WebViewController alloc]init];
            
            self.webVC.viewUrl = URLStr;
//            self.webVC.viewTitle = [self.contentArr[indexPath.row] objectForKey:@"newsTitle"];
            self.webVC.viewTitle = @"搜索详情";
            self.webVC.viewType = @"news";
            self.webVC.weiXun = @"WeiXun";
            
        }
        [self.navigationController pushViewController:self.webVC animated:YES];
    }

    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
